<template>
  <div class="phone-class">
    <div class="entry-container-inner">
      <div class=" published-form__container">
        <div style="background-color: rgb(237, 250, 255);margin-right: auto;margin-left: auto">
          <el-image :src="img" style="width: 100%"></el-image>
          <el-row>
            <div class="phone-title">扬尘治理随手拍</div>
            <p style="margin: 10px">
              为进一步加强扬尘污染防治，提高扬尘污染管控水平，持续打赢蓝天保卫战，我省在落实政府部门监管整治职责的基础上，动员群众参与扬尘污染防治过程，积极拓宽问题来源渠道，以求形成社会共治的良好氛围。</p>
          </el-row>
          <el-row style="padding-top: 10px">
            <el-form :model="dustReportForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
              <el-form-item label="姓名" prop="reporter" align="center" class="dust-el-form-item">
                <el-input v-model="dustReportForm.reporter" placeholder="请输入姓名" style="width: 90%"></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="phoneNumber" align="center" class="dust-el-form-item">
                <el-input v-model="dustReportForm.phoneNumber" placeholder="请输入手机号" style="width: 90%"></el-input>
              </el-form-item>
              <div id="container"></div><!-- 高德地图容器 -->
              <el-form-item label="所属区域" align="center" prop="areaValue" class="dust-el-form-item">
                <el-cascader v-model="dustReportForm.areaValue" :options="cities" :props="props"
                             style="width: 90%"></el-cascader>
              </el-form-item>
              <el-form-item label="扬尘分类" align="center" prop="reportType" class="dust-el-form-item">
                <el-select v-model="dustReportForm.reportType" placeholder="扬尘分类"
                           clearable size="small" style="width: 90%">
                  <el-option v-for="dict in dustOptions" :key="dict.dictValue"
                             :label="dict.dictLabel" :value="dict.dictValue"/>
                </el-select>
              </el-form-item>
              <el-form-item label="手机定位详细地址" align="center" prop="address" class="dust-el-form-item">
                <el-input v-show="dustReportForm.address!=''" v-model="dustReportForm.address" style="width: 90%"
                          :disabled="true"></el-input>
              </el-form-item>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="经度" align="center" v-show="dustReportForm.longitude!=''"
                                class="dust-el-form-item">
                    <el-input v-model="dustReportForm.longitude" style="width: 60%" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="纬度" align="center" v-show="dustReportForm.latitude!=''"
                                class="dust-el-form-item">
                    <el-input v-model="dustReportForm.latitude" style="width: 60%" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <div style="text-align: center">
                <el-button v-show="dustReportForm.address==''&&!addressFlag" @click="getLocation" type="primary"
                           style="background-color: rgb(92, 170, 204)">点击获取位置信息
                </el-button>
                <el-button v-show="dustReportForm.address!=''||addressFlag" @click="getLocation" type="primary"
                           style="background-color: rgb(92, 170, 204)">{{ buttonInfo }}
                </el-button>
              </div>


              <el-form-item label="附件" style="padding-top: 15px;" prop="attachment" align="center"
                            class="dust-el-form-item">
                <Uploader style="margin-right: 40px" url="/api/common/file/localUpload" remark="phone" ref="uploader"/>
              </el-form-item>

              <el-form-item label="扬尘问题说明" align="center" class="dust-el-form-item">
                <el-input type="textarea" style="width: 90%" rows="3" v-model="dustReportForm.remark"
                          placeholder="请详细说明问题情况"></el-input>
              </el-form-item>

              <el-row style="margin: 10px">
                <div style="font-size: 14px">答复</div>
                <p style="
                word-break: break-word;
                color: #666;
                max-width: 100%;
                overflow: visible;
                line-height: 1.5;">我们在收到你的信息后，会尽快核查处理，并及时反馈处理结果，请耐心等待！</p>
              </el-row>

              <el-row>
                <div style="text-align: center;">
                  <a style="font-size: 25px;color: red" @click="goToIndexList">处理结果查询请点击我</a>
                </div>
              </el-row>
              <el-row>
                <div style="text-align: center;padding-top: 10px;padding-bottom: 10px">
                  <el-button type="primary" style="background-color: rgb(92, 170, 204)" @click="submitForm('ruleForm')">
                    提交信息
                  </el-button>
                </div>
              </el-row>
            </el-form>
          </el-row>
        </div>
      </div>
      <footer class="published text-center with-margin-bottom">
        <p class="privacy-collecting-warning" style="opacity: 1;">提交即同意该表单收集您的信息用于后续服务</p>
     <!--   <a target="_blank" class="powered-by" style="opacity: 1;">
          <p>
            <i class="gd-icon-logo powered-logo"></i><span>睿博提供技术支持</span>
          </p>
        </a>
        -->
        </footer>
    </div>
  </div>
</template>

<script>

import request from '@/utils/request'
import {location} from "@/utils/LocationUtil";
import Uploader from "@/components/Uploader";
import {treeselect} from "@/api/regionCode";
import {create as dustReportCreate} from "@/api/weixin/dustReport"


// 登录方法
export function fileUpload(data) {
  return request({
    url: 'api/common/file/localUpload',
    method: 'post',
    data
  })
}

// 验证手机号码
export function checkPhoneNumber(rule, value, callback) {
  const reg = /^1[3|4|5|6|7|8|9]\d{9}$/;
  if (!value) {
    return callback(new Error('请填写手机号码！'))
  } else if (!reg.test(value)) {
    return callback(new Error('请填写正确的手机号码！'))
  } else {
    callback()
  }
}


export default {
  name: "index",
  components: {
    Uploader
  },
  data() {
    return {

      // 城市选择
      cities: [],
      // 区域选择
      areaValue: [],
      // 扬尘分类状态
      dustOptions: [],
      // 图片
      img: require('@/assets/image/tupian.png'),
      dustReportForm: {
        openid: '',
        reporter: '',
        phoneNumber: '',
        areaValue: '',
        reportType: '',
        remark: '',
        address: "",
        latitude: '',
        longitude: '',
        reportStatus:'0',
      },
      buttonInfo: "重新获取当前位置",
      addressFlag: false,
      rules: {
        reporter: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
        ],
        phoneNumber: [
          {required: true, validator: checkPhoneNumber, trigger: 'blur'}
        ],
        areaValue: [
          {required: true, message: '请选择所属区域', trigger: 'blur'}
        ],
        reportType: [
          {required: true, message: '请选择扬尘分类', trigger: 'blur'}
        ],
        address: [
          {required: true, message: '请先获取手机定位', trigger: 'blur'}
        ]
      },
      props: {
        value: 'regionCode',
        label: 'regionName',
        children: 'children'
      },

    };
  },
  created() {

    this.dustReportForm.openid = this.$route.query.openid===undefined?'10086':this.$route.query.openid
    this.getDicts("sys_dust_type").then(response => {
      this.dustOptions = response.data;
    });
  },
  mounted() {
    this.treeselect();
  },

  methods: {
    treeselect() {
      treeselect().then(res => {
        this.cities = res.data;
      }).catch(err => {

      })
    },
    onSubmit(values) {
      console.log('submit', values);
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        let fileList = this.$refs.uploader.fileList;
        this.dustReportForm.reportAttachments = fileList;
        if (valid) {
          dustReportCreate(this.dustReportForm).then(response => {
            this.$router.push('/success')
          })
        } else {
          setTimeout(()=>{
            let isError= document.getElementsByClassName("is-error");
            isError[0].querySelector('input').focus();
          },100);
          return false;

        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleChange(value) {
      console.log(value);
    },
    /**获取地图定位 1*/
    getLocation() {
      const self = this
      self.addressFlag = true;
      self.buttonInfo = "获取位置中..."
      var mapObj = new AMap.Map('container');
      AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位，默认:true
          timeout: 10000,           // 超过10秒后停止定位，默认：无穷大
          maximumAge: 0,            // 定位结果缓存0毫秒，默认：0
          convert: true,            // 自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          showButton: true,         // 显示定位按钮，默认：true
          buttonPosition: 'LB',     // 定位按钮停靠位置，默认：'LB'，左下角
          buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          showMarker: true,         // 定位成功后在定位到的位置显示点标记，默认：true
          showCircle: true,         // 定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true,      // 定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true       // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        })
        mapObj.addControl(geolocation);
        geolocation.getCurrentPosition()
        AMap.event.addListener(geolocation, 'complete', onComplete)
        AMap.event.addListener(geolocation, 'error', onError)


        // 域名需要提升为HTTPS才能走这个回调函数   不然定位存在偏差
        function onComplete(data) {
          // data是具体的定位信息

          self.dustReportForm.address = data.formattedAddress;
          self.dustReportForm.latitude = data.position.lat
          self.dustReportForm.longitude = data.position.lng
          self.buttonInfo = "重新获取当前位置"
        }

        function onError(data) {
          self.buttonInfo = "重新获取当前位置"
          self.getLngLatLocation()
          alert("请打开定位功能！")
          self.dustReportForm.address = "济南大本营";
          self.dustReportForm.latitude = 100
          self.dustReportForm.longitude = 36
        }
      })
    },
    getLngLatLocation() {
      AMap.plugin('AMap.CitySearch', function () {
        var citySearch = new AMap.CitySearch()
        citySearch.getLocalCity(function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            // 查询成功，result即为当前所在城市信息
            //逆向地理编码
            AMap.plugin('AMap.Geocoder', function () {
              debugger
              var geocoder = new AMap.Geocoder({
                // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                city: result.adcode
              })
              var lnglat = result.rectangle.split(';')[0].split(',')
              var lnglat2 = "117.107019,36.701854".split(',');
              geocoder.getAddress(lnglat2, function (status, data) {
                if (status === 'complete' && data.info === 'OK') {

                }
              })
            })
          }
        })
      })
    },
    ready() {
      //百度地图代码下面  这是实例代码  可以填入自己的需求代码
      // 百度地图API功能

      let map = new BMap.Map("container");
      let geolocation = new BMap.Geolocation();
      // 开启SDK辅助定位
      //geolocation.enableSDKLocation();
      geolocation.getCurrentPosition(function (r) {
        debugger
        alert(r.address.city)
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          let mk = new BMap.Marker(r.point);
          map.addOverlay(mk);
          map.panTo(r.point);

          alert('您的位置：' + r.point.lng + ',' + r.point.lat);

        } else {
          alert('failed' + this.getStatus());
        }
      }, {enableHighAccuracy: true})
    },
    goToIndexList() {
      //openid
      this.$router.push({path: '/indexList', query: {openid: this.dustReportForm.openid}})

    }
  },
}
</script>

<style scoped lang="scss">

</style>
